import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_menu/biz/order/detail/option/options_dialog.dart';
import 'package:flutter_menu/biz/order/order_controller.dart';
import 'package:flutter_menu/biz/order/record/shop_car_controller.dart';
import 'package:flutter_menu/model/menu_model.dart';
import 'package:get/get.dart';

class DetailController extends GetxController {
  static DetailController get to => Get.find();

  OrderController orderController = OrderController.to;

  CategoryListProductList? get productInfo =>
      orderController.getProductWithFilterSpec();

  // 菜品Id
  String get productUuid => productInfo?.productUuid ?? '';

  // 菜品名称
  String get productName => productInfo?.imageName ?? '';

  // 菜品图片
  String get productImageUrl => productInfo?.imageUrl ?? '';

  // 菜品是否读取菜单的品名、价格和添加按钮 0否 1是
  bool get productIsRead => productInfo?.isRead == 1;

  // 菜品热区
  String? get productHotZone => productInfo?.hotZone;

  HotZone parseHotZoneFromJson() {
    return HotZone.fromJson(productHotZone ?? "");
  }

  // 菜品价格取自定义菜单中的价格， 有多个规格 取最低的规格价格
  double? get productPrice {
    return productInfo?.getLowestPrice();
  }

  // 是否是套餐
  bool isPackage() => productInfo?.isPackage() ?? false;

  // 是否是多规格
  bool isMultiSpec() => productInfo?.isMultiSpec() ?? false;

  // 规格
  List<DishList> get dishList => productInfo?.dishList ?? [];

  // 当前选择的菜的数量
  var selectedProductNumber = 0.obs;

  // ShopCarItem
  ShopCarItem? shopCarItem;

  void updateProductNumber(int newNumber) {
    if (shopCarItem != null) {
      shopCarItem!.count = newNumber;
      updateShopItem(shopCarItem!);
    }
  }

  void updateShopItem(ShopCarItem item, {bool syncToShopCar = true}) {
    shopCarItem = item;
    selectedProductNumber.value = item.count;
    if (syncToShopCar) {
      ShopCarController.to.addProduct(item);
    }
  }

  // 当前选择的菜的时价
  var newPrice = Rx<num>(900);

  void setNewPrice(num newNumber) {
    newPrice.value = newNumber;
  }

  @override
  void onInit() {
    super.onInit();

    // 从购物车中读取商品数量
    ShopCarItem? item = ShopCarController.to
        .getShopCarItemByProductId(productInfo?.productUuid ?? "");
    if (item != null) {
      updateShopItem(item, syncToShopCar: false);
    }
  }

  @override
  void onReady() {
    super.onReady();

    var showSpecOption = orderController.showSpecOptionDialog;
    if (showSpecOption) {
      showMealOptionsSelectDialog();
      orderController.showSpecOptionDialog = false;
    }
  }

  void showMealOptionsSelectDialog() {
    Get.dialog(
      const OptionsDialog(),
      transitionCurve: Curves.easeIn,
      transitionDuration: const Duration(milliseconds: 100),
    );
  }
}

class HotZone {
  final double left;
  final double right;
  final double top;
  final double bottom;

  static const min = 0.0;
  static const max = 1.0;

  HotZone({
    required this.left,
    required this.right,
    required this.top,
    required this.bottom,
  });

  /// 工厂方法：从 JSON 字符串解析并校验范围
  factory HotZone.fromJson(String jsonString) {
    debugPrint("parse HotZone $jsonString");
    if (jsonString.isEmpty) {
      return HotZone(left: min, right: max, top: min, bottom: max);
    }
    final Map<String, dynamic> jsonData = jsonDecode(jsonString);

    // 提取并校验每个值
    final double left = _validateRange(jsonData['left']);
    final double right = _validateRange(jsonData['right'], isStart: false);
    final double top = _validateRange(jsonData['top']);
    final double bottom = _validateRange(jsonData['bottom'], isStart: false);

    return HotZone(left: left, right: right, top: top, bottom: bottom);
  }

  /// 校验值是否在 0 到 1 范围内
  static double _validateRange(dynamic value, {bool isStart = true}) {
    if (value == null || value is! num) {
      return isStart ? min : max;
    }
    final double doubleValue = value.toDouble();
    if (doubleValue < min || doubleValue > max) {
      return isStart ? min : max;
    }
    return doubleValue;
  }

  /// 转换为 JSON 字符串
  String toJsonString() {
    final Map<String, dynamic> jsonData = {
      'left': left,
      'right': right,
      'top': top,
      'bottom': bottom,
    };
    return jsonEncode(jsonData);
  }

  @override
  String toString() {
    return 'HotZone(left: $left, right: $right, top: $top, bottom: $bottom)';
  }
}
